package com.huizu.web.controller.monitor;

import cn.hutool.core.util.StrUtil;
import com.huizu.common.config.CasProperties;
import com.huizu.common.core.domain.model.LoginUser;
import com.huizu.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
@RequestMapping("/affairs")
public class CasLoginController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CasProperties casProperties;

    @GetMapping(value = "/casLogin")
    public void login(String url, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println(url);
        // 只是为了跳转到cas服务端的登录页面  登录成功后会跳回此页
        // 可根据自身系统进行代码增强
        // 获取当前用户信息
        LoginUser userDetails = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String token = tokenService.createToken(userDetails);
        if (StrUtil.isNotBlank(url)) {
            response.sendRedirect(url + "?token=" + token);
        } else {
            response.sendRedirect(casProperties.getManagerUrl() + "?token=" + token);
        }
    }
}
